package com.yaodian100.ec.giftcard.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.csvreader.CsvWriter;
import com.yaodian100.core.admin.utils.AdminHelper;
import com.yaodian100.core.common.dao.ObjectDao;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.giftcard.entity.GiftcardAmount;
import com.yaodian100.ec.giftcard.entity.GiftcardItem;
import com.yaodian100.ec.giftcard.entity.GiftcardMain;
import com.yaodian100.ec.giftcard.entity.GiftcardReceiveItem;
import com.yaodian100.ec.giftcard.entity.GiftcardReceiveMain;
import com.yaodian100.ec.giftcard.service.GiftcardService;
import com.yaodian100.ec.giftcard.service.vo.ReceiveGiftcardVo;
import com.yaodian100.ec.member.entity.VirtualBalance;
import com.yaodian100.ec.member.service.MemberService;

public class GiftcardServiceImpl extends DomainServiceImpl<GiftcardMain> implements GiftcardService {
	private ObjectDao<GiftcardAmount> giftcardAmountDao;
	private ObjectDao<GiftcardItem> giftcardItemDao;
	private ObjectDao<GiftcardReceiveMain> giftcardReceiveMainDao;
	private ObjectDao<GiftcardReceiveItem> giftcardReceiveItemDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private MemberService memberService;

	@Override
	public List<Object> queryGiftcard(String giftcardName,String applyDate
			, String giftcardQueryStatus, SimplePager pager) throws Exception {
		List<Object> resultList=new ArrayList<Object>();
		
		CommonCriteria crit = new CommonCriteria();
		if(giftcardName!=null && !giftcardName.isEmpty())
			crit.addRlike("giftcardName", giftcardName);
		
		if(applyDate!=null && !applyDate.isEmpty()){
			DateFormat format=new SimpleDateFormat(EcConstant.PATTERN_TIMESTAMP);
			crit.addLe("applyDate", format.parse(applyDate+" 23:59:59"));
			crit.addGe("applyDate", format.parse(applyDate+" 00:00:00"));
		}
		List<GiftcardMain> giftcardMains = this.getDao().getList(crit, null);
		
		Map<Long,GiftcardMain> giftcardMainMap=new TreeMap<Long,GiftcardMain>();
		List<GiftcardAmount> giftcardAmounts=new ArrayList<GiftcardAmount>();
		if(giftcardMains!=null && giftcardMains.size()>0){
			List<Long> mainIds=new ArrayList<Long>();
			for(int i=0;i<giftcardMains.size();i++){
				GiftcardMain giftcardMain=giftcardMains.get(i);
				mainIds.add(giftcardMain.getMainId());
				
				giftcardMainMap.put(giftcardMain.getMainId(),giftcardMain);
			}
			
			crit = new CommonCriteria();
			crit.addIn("mainId",mainIds);
			if(!"-1".equals(giftcardQueryStatus))
				crit.addEq("status",giftcardQueryStatus);
			
			pager.setTotalSize(giftcardAmountDao.getListSize(crit).intValue());
			giftcardAmounts=giftcardAmountDao.getListPageable(crit, new String[]{"mainId desc"}
					, pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord());
		}
		
		resultList.add(giftcardMainMap);
		resultList.add(giftcardAmounts);
		
		return resultList;
	}
	
	@Override
	@Transactional(readOnly = false)
	public void generate(GiftcardMain giftcardMain, String[] amount, String[] count) throws CoreException {
		giftcardMain=this.save(giftcardMain);
		
		List<GiftcardAmount> giftcardAmounts=new ArrayList<GiftcardAmount>();
		for(int i=0;i<amount.length;i++){
			if("".equals(amount[i]) || "0".equals(amount[i]) || "".equals(count[i]) || "0".equals(count[i]))
				continue;
			
			GiftcardAmount giftcardAmount=new GiftcardAmount();
			giftcardAmount.setMainId(giftcardMain.getMainId());
			giftcardAmount.setAmount(new BigDecimal(amount[i]));
			giftcardAmount.setCount(Integer.parseInt(count[i]));
			giftcardAmount.setReceiveCount(0);
			giftcardAmount.setStatus("00");
			giftcardAmount=giftcardAmountDao.save(giftcardAmount);
			
			giftcardAmounts.add(giftcardAmount);
		}
		
		DateFormat format=new SimpleDateFormat("yy");
		String yyStr=format.format(new Date());
		
		String sql="SELECT MAX(CARD_CODE) CARD_CODE FROM EC_GIFTCARD_ITEM";
		Map sqlMap=jdbcTemplate.queryForMap(sql);
		String maxCardCode=(String)sqlMap.get("CARD_CODE");
		
		int cardCodeInt;
		if(maxCardCode==null || !maxCardCode.substring(0,2).equals(yyStr)){
			cardCodeInt=Integer.parseInt(yyStr+"00000000");
		}else{
			cardCodeInt=Integer.parseInt(maxCardCode);
		}
		
		for(int i=0;i<giftcardAmounts.size();i++){
			GiftcardAmount giftcardAmount=giftcardAmounts.get(i);
			
			for(int j=0;j<giftcardAmount.getCount();j++){
				GiftcardItem giftcardItem=new GiftcardItem();
				giftcardItem.setAmountId(giftcardAmount.getAmountId());
				
				cardCodeInt++;
				String cardCodeStr=new Integer(cardCodeInt).toString();
				giftcardItem.setCardCode(cardCodeStr);
				giftcardItem.setCardCheckCode(this.generateCardCheckCode(cardCodeStr));
				giftcardItem.setCardPassword(this.generateCardPassword());
				giftcardItem.setStatus("00");
				giftcardItem.setRechargeDeadline(giftcardMain.getRechargeDeadline());
				giftcardItem.setRechargeStatus("0");
				
				giftcardItemDao.save(giftcardItem);
			}
		}
	}
	
	@Override
	public List<GiftcardAmount> getGiftcardAmountsByMainId(Long mainId) throws Exception {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("mainId",mainId);
		List<GiftcardAmount> giftcardAmounts=giftcardAmountDao.getList(crit, new String[]{"amount desc"});
		
		return giftcardAmounts;
	}
	
	@Override
	public GiftcardAmount getGiftcardAmountByAmountId(Long amountId) throws Exception {
		return giftcardAmountDao.get(amountId);
	}
	
	@Override
	public List<GiftcardItem> getGiftcardItemsByAmountId(Long amountId) throws Exception {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("amountId",amountId);
		List<GiftcardItem> giftcardItems=giftcardItemDao.getList(crit, new String[]{"itemId asc"});
		
		return giftcardItems;
	}
	
	@Override
	@Transactional(readOnly = false)
	public InputStream exportGiftcard(Long amountId) throws Exception {
		ByteArrayOutputStream output=new ByteArrayOutputStream();
		CsvWriter w=new CsvWriter(output, ',', Charset.forName("UTF-8"));
		w.writeRecord(new String[]{"Code","Password","Amount","Recharge Deadline"});
		GiftcardAmount giftcardAmount=this.getGiftcardAmountByAmountId(amountId);
		List<GiftcardItem> giftcardItems=this.getGiftcardItemsByAmountId(amountId);
		for (GiftcardItem giftcardItem : giftcardItems){
			String cardCodeStr=giftcardItem.getCardCode();
			String cardCode=cardCodeStr+giftcardItem.getCardCheckCode();
			
			DateFormat format=new SimpleDateFormat(EcConstant.PATTERN_TIMESTAMP);
			String rechargeDeadline=format.format(giftcardItem.getRechargeDeadline());
			w.writeRecord(new String[]{cardCode,giftcardItem.getCardPassword(),giftcardAmount.getAmount().toString()
							,rechargeDeadline});
		}
		
		w.flush();
		w.close();
		InputStream inputStream=new ByteArrayInputStream(output.toByteArray());
		output.flush();
		output.close();
		
		giftcardAmount.setStatus("10");
		giftcardAmountDao.save(giftcardAmount);
		
		return inputStream;
	}
	
	@Override
	@Transactional(readOnly = false)
	public void warehouseGiftcard(Long amountId) throws CoreException {
		GiftcardAmount giftcardAmount=giftcardAmountDao.get(amountId);
		giftcardAmount.setStatus("50");
		giftcardAmountDao.save(giftcardAmount);
		
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("amountId",amountId);
		List<GiftcardItem> giftcardItems=giftcardItemDao.getList(crit, null);
		Date now=new Date();
		for(int i=0;i<giftcardItems.size();i++){
			GiftcardItem giftcardItem=giftcardItems.get(i);
			giftcardItem.setStatus("50");
			giftcardItem.setWarehouseDate(now);
			giftcardItemDao.save(giftcardItem);
		}
	}
	
	@Override
	@Transactional(readOnly = false)
	public void cancelGiftcard(Long amountId) throws CoreException {
		GiftcardAmount giftcardAmount=giftcardAmountDao.get(amountId);
		giftcardAmount.setStatus("90");
		giftcardAmountDao.save(giftcardAmount);
		
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("amountId",amountId);
		List<GiftcardItem> giftcardItems=giftcardItemDao.getList(crit, null);
		for(int i=0;i<giftcardItems.size();i++){
			GiftcardItem giftcardItem=giftcardItems.get(i);
			giftcardItem.setStatus("90");
			giftcardItemDao.save(giftcardItem);
		}
	}
	
	@Override
	public List<GiftcardItem> queryGiftcardItems(Long amountId,SimplePager pager) throws Exception {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("amountId",amountId);
		pager.setTotalSize(giftcardItemDao.getListSize(crit).intValue());
		List<GiftcardItem> giftcardItems=giftcardItemDao.getListPageable(crit, new String[]{"itemId asc"}
		, pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord());
		
		return giftcardItems;
	}
	
	private String generateCardCheckCode(String cardCodeStr){
		int sumInt=0;
		int countInt=11;
		for(int i=0;i<10;i++){
			int number;
			if(i==9){
				number=new Integer(cardCodeStr.substring(i));
			}else{
				number=new Integer(cardCodeStr.substring(i,i+1));
			}
			
			sumInt=sumInt+(number*countInt*9);
			countInt--;
		}
		
		String sumStr=new Integer(sumInt).toString();
		
		return sumStr.substring(sumStr.length()-1);
	}
	
	private String generateCardPassword(){
		String[] strArray={"2","3","4","5","6","7","8","9",
				"A","B","C","D","E","F","G","H","J","K","L","M",
				"N","P","Q","R","S","T","U","V","W","X","Y","Z"};
		
		String password="";
		while(password.length() < 8){
			int index=(int)(Math.random()*32);
			password=password+strArray[index];
		}
		
		return password;
	}
	
	@Override
	public List<Object> queryReceiveGiftcard(Long receiveId,String applyDateStart,String applyDateEnd
			,String receiveDateStart,String receiveDateEnd,String approveDateStart,String approveDateEnd
			,String giftcardReceiveQueryStatus,String receiveUser,String applyUser,SimplePager pager)
		throws Exception {
		List<Object> resultList=new ArrayList<Object>();
		
		CommonCriteria crit = new CommonCriteria();
		if(receiveId!=null)
			crit.addEq("receiveId", receiveId);
		
		DateFormat format=new SimpleDateFormat(EcConstant.PATTERN_TIMESTAMP);
		if(applyDateStart!=null && !applyDateStart.isEmpty()){
			crit.addGe("applyDate", format.parse(applyDateStart+" 00:00:00"));
		}
		
		if(applyDateEnd!=null && !applyDateEnd.isEmpty()){
			crit.addLe("applyDate", format.parse(applyDateEnd+" 23:59:59"));
		}
		
		if(receiveDateStart!=null && !receiveDateStart.isEmpty()){
			crit.addGe("receiveDate", format.parse(receiveDateStart+" 00:00:00"));
		}
		
		if(receiveDateEnd!=null && !receiveDateEnd.isEmpty()){
			crit.addLe("receiveDate", format.parse(receiveDateEnd+" 23:59:59"));
		}
		
		if(approveDateStart!=null && !approveDateStart.isEmpty()){
			crit.addGe("approveDate", format.parse(approveDateStart+" 00:00:00"));
		}
		
		if(approveDateEnd!=null && !approveDateEnd.isEmpty()){
			crit.addLe("approveDate", format.parse(approveDateEnd+" 23:59:59"));
		}
		
		if(!"-1".equals(giftcardReceiveQueryStatus))
			crit.addEq("status",giftcardReceiveQueryStatus);
		
		if(receiveUser!=null && !receiveUser.isEmpty())
			crit.addRlike("receiveUser",receiveUser);
		
		if(applyUser!=null && !applyUser.isEmpty())
			crit.addRlike("applyUser",applyUser);
		
		List<GiftcardReceiveMain> giftcardReceiveMains = giftcardReceiveMainDao.getList(crit, null);
		
		Map<Long,GiftcardReceiveMain> giftcardReceiveMainMap=new TreeMap<Long,GiftcardReceiveMain>();
		List<GiftcardReceiveItem> giftcardReceiveItems=new ArrayList<GiftcardReceiveItem>();
		if(giftcardReceiveMains!=null && giftcardReceiveMains.size()>0){
			List<Long> receiveIds=new ArrayList<Long>();
			for(int i=0;i<giftcardReceiveMains.size();i++){
				GiftcardReceiveMain giftcardReceiveMain=giftcardReceiveMains.get(i);
				receiveIds.add(giftcardReceiveMain.getReceiveId());
				
				giftcardReceiveMainMap.put(giftcardReceiveMain.getReceiveId(),giftcardReceiveMain);
			}
			
			crit = new CommonCriteria();
			crit.addIn("receiveId",receiveIds);
			
			pager.setTotalSize(giftcardReceiveItemDao.getListSize(crit).intValue());
			giftcardReceiveItems=giftcardReceiveItemDao.getListPageable(crit, new String[]{"receiveId desc"}
					, pager.getCurrentPage() * pager.getPageRecord(), pager.getPageRecord());
		}
		
		resultList.add(giftcardReceiveMainMap);
		resultList.add(giftcardReceiveItems);
		
		return resultList;
	}
	
	@Override
	public boolean checkGiftcardCode(String giftcardCode) throws Exception {
		String cardode=giftcardCode.replaceAll("-","").substring(0,10);
		String cardCheckCode=giftcardCode.replaceAll("-","").substring(10);
		
		String sql="SELECT COUNT(*) FROM EC_GIFTCARD_ITEM WHERE CARD_CODE=? AND CARD_CHECK_CODE=?";
		int count=jdbcTemplate.queryForInt(sql, cardode,cardCheckCode);
		
		if(count==0) return false;
		
		return  true;
	}
	
	@Override
	public List<Object> queryAddReceiveGiftcard(String startGiftcardCode,Integer giftcardCount) throws Exception {
		int startCardCode=Integer.parseInt(startGiftcardCode.replaceAll("-","").substring(0,10));
		int endCardCode=startCardCode+(giftcardCount-1);
		
		String sql="SELECT * FROM EC_GIFTCARD_ITEM WHERE CARD_CODE BETWEEN ? AND ? ORDER BY CARD_CODE ASC";
		List giftcardItems=jdbcTemplate.queryForList(sql, startCardCode+"",endCardCode+"");
		List errList=new ArrayList();
		
		int runCount=endCardCode-startCardCode+1;
		Long tempAmountId=null;
		List<Map> showList=new ArrayList<Map>();
		int itemCount=0;
		for(int i=0;i<runCount;i++){
			Map errMap=new TreeMap();
			if(i!=0) startCardCode++;
			
			if(i>=giftcardItems.size()){
				Map map=new TreeMap();
				errMap.put("msg","超出总卡号范围："+(runCount-giftcardItems.size())+"笔");
				errList.add(errMap);
				break;
			}
			
			Map map=(Map)giftcardItems.get(i);
			String cardCode=(String)map.get("CARD_CODE");
			if(!(startCardCode+"").equals(cardCode)){
				errMap.put("msg","无此卡号");
				errMap.put("giftcardItemMap",map);
				errList.add(errMap);
				continue;
			}
			
			String status=(String)map.get("STATUS");
			if(!"50".equals(status)){
				errMap.put("msg","此卡号状态不为已入库");
				errMap.put("giftcardItemMap",map);
				errList.add(errMap);
				continue;
			}
			
			itemCount++;
			Long amountId=((BigDecimal)map.get("AMOUNT_ID")).longValue();
			if(tempAmountId==null){
				showList.add(this.getAmountMap(amountId));
				tempAmountId=amountId;
			}else if(tempAmountId!=amountId){
				showList.get(showList.size()-1).put("COUNT",itemCount);
				itemCount=0;
				showList.add(this.getAmountMap(amountId));
				tempAmountId=amountId;
			}
		}
		
		if(showList.size()>0){
			showList.get(showList.size()-1).put("COUNT",itemCount);
		}
		
		List resultList=new ArrayList();
		resultList.add(showList);
		resultList.add(errList);
		
		return resultList;
	}
	
	private Map getAmountMap(Long amountId){
		String sql="SELECT GM.GIFTCARD_NAME,GA.AMOUNT FROM EC_GIFTCARD_MAIN GM,EC_GIFTCARD_AMOUNT GA " +
		"WHERE GA.MAIN_ID=GM.MAIN_ID AND AMOUNT_ID=?";
		Map amountMap=jdbcTemplate.queryForMap(sql,amountId);
		
		return amountMap;
	}
	
	@Override
	@Transactional(readOnly = false)
	public GiftcardReceiveMain receiveGiftcard(ReceiveGiftcardVo receiveGiftcardVo) throws CoreException {
		Date now=new Date();
		
		GiftcardReceiveMain giftcardReceiveMain=new GiftcardReceiveMain();
		giftcardReceiveMain.setApplyUser(receiveGiftcardVo.getReceiveApplyUser());
		giftcardReceiveMain.setApplyDate(now);
		giftcardReceiveMain.setApplyCount(receiveGiftcardVo.getGiftcardCount());
		giftcardReceiveMain.setApplyDesc(receiveGiftcardVo.getReceiveApplyDesc());
		giftcardReceiveMain.setStatus("00");
		giftcardReceiveMain.setReceiveTotal(receiveGiftcardVo.getReceiveTotalAmount());
		giftcardReceiveMain.setReceiveUser(AdminHelper.getUser().getUsername());
		giftcardReceiveMain=giftcardReceiveMainDao.save(giftcardReceiveMain);
		
		int startCardCode=Integer.parseInt(receiveGiftcardVo.getStartGiftcardCode()
				.replaceAll("-","").substring(0,10));
		int endCardCode=startCardCode+(receiveGiftcardVo.getGiftcardCount()-1);
		
		String updateSql="UPDATE EC_GIFTCARD_ITEM SET RECEIVE_ID=?,STATUS=?,RECEIVE_DATE=? " +
							"WHERE CARD_CODE BETWEEN ? AND ?";
		jdbcTemplate.update(updateSql,giftcardReceiveMain.getReceiveId(),"60",now,startCardCode+"",endCardCode+"");
		
		Integer[] receiveItemCounts=receiveGiftcardVo.getReceiveItemCounts();
		BigDecimal[] receiveItemAmounts=receiveGiftcardVo.getReceiveItemAmounts();
		for(int i=0;i<receiveItemCounts.length;i++){
			GiftcardReceiveItem giftcardReceiveItem=new GiftcardReceiveItem();
			giftcardReceiveItem.setReceiveId(giftcardReceiveMain.getReceiveId());
			giftcardReceiveItem.setAmount(receiveItemAmounts[i]);
			giftcardReceiveItem.setCount(receiveItemCounts[i]);
			giftcardReceiveItemDao.save(giftcardReceiveItem);
		}
		
		return giftcardReceiveMain;
	}
	
	@Override
	@Transactional(readOnly = false)
	public void publishGiftcard(Long receiveId) throws CoreException {
		GiftcardReceiveMain giftcardReceiveMain=giftcardReceiveMainDao.get(receiveId);
		giftcardReceiveMain.setStatus("40");
		giftcardReceiveMain.setReceiveDate(new Date());
		giftcardReceiveMainDao.save(giftcardReceiveMain);
	}
	
	@Override
	public GiftcardReceiveMain getGiftcardReceiveMainByReceiveId(Long receiveId) throws Exception {
		return giftcardReceiveMainDao.get(receiveId);
	}

	@Override
	public List<GiftcardReceiveItem> getGiftcardReceiveItemsByReceiveId(Long receiveId) throws Exception {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("receiveId", receiveId);
		List<GiftcardReceiveItem> giftcardReceiveItems=giftcardReceiveItemDao.getList(crit,new String[]{"receiveItemId asc"});
		
		return giftcardReceiveItems;
	}
	
	@Override
	public InputStream exportReceiveItems(Long receiveId) throws Exception {
		ByteArrayOutputStream output=new ByteArrayOutputStream();
		CsvWriter w=new CsvWriter(output, ',', Charset.forName("UTF-8"));
		w.writeRecord(new String[]{"Code","Amount","Recharge Deadline"});
		
		String sql="SELECT GI.CARD_CODE,GI.CARD_CHECK_CODE,GA.AMOUNT,GI.RECHARGE_DEADLINE " +
				"FROM EC_GIFTCARD_ITEM GI,EC_GIFTCARD_AMOUNT GA " +
				"WHERE GI.AMOUNT_ID=GA.AMOUNT_ID AND GI.RECEIVE_ID=? ORDER BY GI.CARD_CODE ASC";
		List receiveItems=jdbcTemplate.queryForList(sql,receiveId);
		
		
		
		for(int i=0;i<receiveItems.size();i++){
			Map map=(Map)receiveItems.get(i);
			String cardCodeStr=(String)map.get("CARD_CODE");
			String cardCheckCodeStr=(String)map.get("CARD_CHECK_CODE");
			String cardCode=cardCodeStr+cardCheckCodeStr;
//			String cardCode=cardCodeStr.substring(0,2)+"-"+cardCodeStr.substring(2,6)+"-"+cardCodeStr.substring(6)
//								+"-"+cardCheckCodeStr;
			
			BigDecimal amount=(BigDecimal)map.get("AMOUNT");
			
			DateFormat format=new SimpleDateFormat(EcConstant.PATTERN_TIMESTAMP);
			String rechargeDeadline=format.format((Date)map.get("RECHARGE_DEADLINE"));
			w.writeRecord(new String[]{cardCode,amount.toString(),rechargeDeadline});
		}
		
		w.flush();
		w.close();
		InputStream inputStream=new ByteArrayInputStream(output.toByteArray());
		output.flush();
		output.close();
		
		return inputStream;
	}
	
	@Override
	@Transactional(readOnly = false)
	public void approve(Long receiveId, boolean isApprove,String disapproveReason) throws CoreException {
		Date now=new Date();
		String updateStatus;
		
		GiftcardReceiveMain giftcardReceiveMain=giftcardReceiveMainDao.get(receiveId);
		if(isApprove){
			giftcardReceiveMain.setStatus("50");
			updateStatus="70";
		}else{
			giftcardReceiveMain.setStatus("90");
			giftcardReceiveMain.setDisapproveReason(disapproveReason);
			updateStatus="50";
		}
		giftcardReceiveMain.setApproveUser(AdminHelper.getUser().getUsername());
		giftcardReceiveMain.setApproveDate(now);
		giftcardReceiveMainDao.save(giftcardReceiveMain);
		
		String updateSql="UPDATE EC_GIFTCARD_ITEM SET STATUS=? WHERE RECEIVE_ID=?";
		jdbcTemplate.update(updateSql,updateStatus,receiveId);
	}
	
	/**
	 * returnCode
	 * 0:正常
	 * 1:無此卡號or卡片狀態不為核可狀態or密码错误
	 * 2:已過期
	 * 3:已開過卡
	 * 4:卡号正确，但尚未核可
	 */
	@Override
	public int checkCardCode(String cardCode,String cardPassword) throws Exception {
		String code=cardCode.replaceAll("-","").substring(0,10);
		String checkCode=cardCode.replaceAll("-","").substring(10);
		
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("cardCode", code);
		crit.addEq("cardCheckCode", checkCode);
		GiftcardItem giftcardItem=giftcardItemDao.getSingle(crit, null);
		if(giftcardItem==null)
			return 1;
		
		if(!"70".equals(giftcardItem.getStatus()))
			return 4;
		
		Date now=new Date();
		Date deadline=giftcardItem.getRechargeDeadline();
		if(now.after(deadline))
			return 2;
		
		if(!"0".equals(giftcardItem.getRechargeStatus()))
			return 3;
		
		if(!StringUtils.defaultString(cardPassword).toUpperCase().equals(giftcardItem.getCardPassword())) {
			return 1;
		}
		return 0;
	}
	
	@Override
	public GiftcardAmount getGiftcardAmountByCardCode(String cardCode) throws Exception {
		GiftcardItem giftcardItem=this.getGiftcardItemByCardCode(cardCode);
		GiftcardAmount giftcardAmount=giftcardAmountDao.get(giftcardItem.getAmountId());
		
		return giftcardAmount;
	}
	
	@Override
	public GiftcardItem getGiftcardItemByCardCode(String cardCode) throws Exception {
		String code=cardCode.replaceAll("-","").substring(0,10);
		String checkCode=cardCode.replaceAll("-","").substring(10);
		
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("cardCode", code);
		crit.addEq("cardCheckCode", checkCode);
		GiftcardItem giftcardItem=giftcardItemDao.getSingle(crit, null);
		
		return giftcardItem;
	}
	
	@Override
	@Transactional(readOnly = false)
	public void rechargeGiftcard(VirtualBalance virtualBalance,GiftcardItem giftcardItem) throws CoreException {
		try{
			memberService.saveOrUpdateVirtualBalance(virtualBalance);
			giftcardItemDao.update(giftcardItem);
		}catch(Exception e){
			e.printStackTrace();
			throw new CoreException();
		}
	}
	
	//getter & setter
	public ObjectDao<GiftcardAmount> getGiftcardAmountDao() {
		return giftcardAmountDao;
	}

	public void setGiftcardAmountDao(ObjectDao<GiftcardAmount> giftcardAmountDao) {
		this.giftcardAmountDao = giftcardAmountDao;
	}

	public ObjectDao<GiftcardItem> getGiftcardItemDao() {
		return giftcardItemDao;
	}

	public void setGiftcardItemDao(ObjectDao<GiftcardItem> giftcardItemDao) {
		this.giftcardItemDao = giftcardItemDao;
	}

	public ObjectDao<GiftcardReceiveMain> getGiftcardReceiveMainDao() {
		return giftcardReceiveMainDao;
	}

	public void setGiftcardReceiveMainDao(
			ObjectDao<GiftcardReceiveMain> giftcardReceiveMainDao) {
		this.giftcardReceiveMainDao = giftcardReceiveMainDao;
	}

	public ObjectDao<GiftcardReceiveItem> getGiftcardReceiveItemDao() {
		return giftcardReceiveItemDao;
	}

	public void setGiftcardReceiveItemDao(
			ObjectDao<GiftcardReceiveItem> giftcardReceiveItemDao) {
		this.giftcardReceiveItemDao = giftcardReceiveItemDao;
	}
}